#include "ros/ros.h"
#include "geometry_msgs/Twist.h"
#include "std_srvs/Trigger.h"

//全局的发布者
ros::Publisher turtle_vel_pub;
//标志位，标志海龟是运动还是停止
bool pubCommand = false;

//service回调函数，输入参数request,输出参数response
bool commandCallBack(std_srvs::Trigger::Request &req, std_srvs::Trigger::Response &res)
{
    pubCommand = !pubCommand;

    //显示请求数据
    ROS_INFO("Publisher turtle velocity command [%s]", pubCommand==true?"yes":"no");

    //设置反馈数据
    res.success = true;
    res.message = "Change turtle command state";

    return true;
}

int main(int argc, char** argv)
{
    ros::init(argc, argv, "turtle_command_server");

    ros::NodeHandle n;

    //创建一个server，注册回调函数
    //收到service则回调
    ros::ServiceServer command_server = n.advertiseService("/turtle_command", commandCallBack);

    //创建一个publisher，发布名为/turtle1/cmd_vel的topic
    turtle_vel_pub = n.advertise<geometry_msgs::Twist>("/turtle1/cmd_vel", 10);

    //循环等待回调函数
    ROS_INFO("Ready to receive turtle command!");

    ros::Rate loop_rate(10);

    while(ros::ok()){
        //查看一次回调函数队列，有request跳入回调函数
        ros::spinOnce();

        //如果标志位true，则发布速度指令
        if(pubCommand)
        {
            geometry_msgs::Twist vel_msg;
            vel_msg.linear.x = 0.5;
            vel_msg.angular.z = 0.2;
            turtle_vel_pub.publish(vel_msg);
        }

        loop_rate.sleep();
    }

    return 0;
}
